#include "menu_list.h"
#include <memories/MEDSdcard.h>
#include <tsd/tsd.h>
#include <pit/pitd.h>

menu_list_p menu_list_init (menu_list_p list, char * dir_name) {
    FILINFO fi;
    DIR *dir;

    f_opendir(&(list->dir), dir_name);

    // Copy directory object.
    dir = &(list->dir);

    //  Rewind the directory object.
    if (FR_OK != f_readdir(dir, 0)) {
        return 0;
    }

    // Count number of entries.
    list->size = 0;
    while (1) {
        if (FR_OK != f_readdir(dir, &fi)) {
            return 0;
        }
        if (fi.fname[0] == 0) {
            break;
        }
        (list->size)++;
    }

    // Set flags.
    list->flags = 0;
    if (dir->sclust == 0) {
        list->flags |= MENU_LIST_IS_ROOT;
    }

    return list;
}

menu_item_p menu_list_get (menu_item_p item, menu_list_p list, unsigned int idx) {
    FILINFO fi;
    DIR * dir;
    int i;
    char *in;
    char *ine;
    char *fn;

    if (idx >= list->size) {
        return 0;
    }

    // search
    dir = &(list->dir);
    f_readdir(dir, 0);
    for (i = 0; i <= idx; ++i) {
        if (FR_OK != f_readdir(dir, &fi)) {
            return 0;
        }
    }

    // copy name
    in = item->name;
    ine = item->name + MENU_ITEM_NAME_LENGTH - 1;
    fn = fi.fname;
    for (;(*fn != 0) && (in < ine);
            ++fn, ++in) {
        *in = *fn;
    }
    *in = 0;

    // set flags
    item->flags = 0;
    if (fi.fattrib & AM_DIR) {
        item->flags |= MENU_ITEM_IS_DIR;
    }

    return item;
}
